import {
    reqlogin
} from "../../http/api"
import {
    successAlert
} from "../../utils/alert"
// 初始值
const initState = {
    //1.1初始化表单数据
    user: {
        phone: "",
        password: ""
    },
    // 2.1用户信息
    info: sessionStorage.getItem("info")?JSON.parse(sessionStorage.getItem("info")):{}
}

//actionTYpes
const types = {
    // 1.2.修改user type
    change_user: "login_change_user",
    //2.2 修改info
    change_info: "login_change_info"
}

//reducer 
const reducer = (state = initState, action) => {
    switch (action.type) {
        // 1.3 修改user 
        // {type:types.change_user,key:"phone",value:"110"}
        case types.change_user:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
            break;
            // 2.3 修改info
            // {type:types.change_user,info:{token:"1231"}}
        case types.change_info:

            return {
                ...state,
                info: action.info
            }
            break;
        default:
            return state;
    }
}

//actionCreators
export const actions = {
    // 1.4修改user action 
    changeUser: (key, value) => ({
        type: types.change_user,
        key,
        value
    }),
    // 2.4修改info action 
    changeInfo: (info) => {
        // 同步到本地存储
        if(info.token){
            sessionStorage.setItem("info",JSON.stringify(info))
        }else{
            sessionStorage.removeItem("info")
        }
        return {
            type: types.change_info,
            info
        }
    },
    //1.6登录
    reqLogin: (history) => async (dispatch, getState) => {
        let {
            user
        } = getState().login
        let res = await reqlogin(user);
        if (res.data.code == 200) {
            //弹成功
            successAlert(res.data.msg)
            //存用户信息
            dispatch(actions.changeInfo(res.data.list))

            //跳转页面
            history.push("/index/home")
        }
    }
}

//selector 导出数据
// 1.5导出user 
export const getUser = state => state.login.user;

// 2.5导出info 
export const getInfo = state => state.login.info;


//导出reducer
export default reducer